package com.sky.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.EmployeeUpdateDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    //前端bug，修改密码不传id，只能在这存储id
    private Long id;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对传过来的密码做md5加密处理

        password = DigestUtils.md5DigestAsHex(password.getBytes());
//        password = DigestUtil.md5Hex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        this.id = employee.getId();

        //3、返回实体对象
        return employee;
    }

    @Override
    public void saveEmp(EmployeeDTO employeeDTO) {
        log.info("当前线程ID：{} 业务层",Thread.currentThread().getId());

//        1.给实体类赋值
         Employee employee = new Employee();
         BeanUtils.copyProperties(employeeDTO,employee);
//      2. 设置密码，创建修改时间，创建修改人，状态
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setCreateTime(LocalDateTime.now());
        employee.setStatus(1);
//        先添加假数据
//         Long currentId = BaseContext.getCurrentId();
//        employee.setCreateUser(currentId);
//        employee.setUpdateUser(currentId);

        employeeMapper.insert(employee);

    }

    @Override
    public PageResult page(EmployeePageQueryDTO dto) {
//        1.开启分页查询
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
//        2. 调用Mapper查询数据
      Page page= employeeMapper.pageQuery(dto);
//      3.封装结果
         PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }

    @Override
    public void startOrStop(Integer status, Long id) {

         Employee employee = Employee.builder()
                .id(id)
                .status(status)
//                .updateUser(BaseContext.getCurrentId())
//                .updateTime(LocalDateTime.now())
                .build();

        employeeMapper.update(employee);

    }

    @Override
    public Employee getById(Long id) {

        return employeeMapper.getById(id);
    }

    @Override
    public void update(Employee employee) {

//        employee.setUpdateUser(BaseContext.getCurrentId());
//        employee.setUpdateTime(LocalDateTime.now());

        employeeMapper.update(employee);


    }

    @Override
    public boolean updatePassword(EmployeeUpdateDTO employeeUpdateDTO) {
        Employee employee = new Employee();
        String oldPassword =DigestUtils.md5DigestAsHex(employeeUpdateDTO.getOldPassword().getBytes());
        if(employeeMapper.getById(this.id).getPassword().equals(oldPassword)){
            //密码正确
            employee.setId(this.id);
            employee.setPassword(DigestUtils.md5DigestAsHex(employeeUpdateDTO.getNewPassword().getBytes()));
            employeeMapper.update(employee);
            return true;
        }else{
            //密码错误
            return false;
        }
    }

}
